package cn.yhjz.live.constroller;

import cn.yhjz.live.trans.TransPushFFMPEG;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/live")
@Slf4j
public class LiveController {

    public static Map<String, TransPushFFMPEG> TRANS_PUSH_MAP = new ConcurrentHashMap<>();

    /**
     * 订阅一个rtsp地址，返回websocket地址
     *
     * @param body
     * @return
     */
    @RequestMapping("/subscribe")
    public String subscribe(@RequestBody JSONObject body) {
        String source = body.getString("source");
        String sourceHash = getHash(source);
        //启动ffmpeg转码
        TransPushFFMPEG transPush = new TransPushFFMPEG();
        TRANS_PUSH_MAP.put(sourceHash, transPush);
        transPush.setSourceUrl(source);
        transPush.start();
        return sourceHash;
    }

    @RequestMapping("/unsubscribe")
    public String unsubscribe(@RequestBody JSONObject body) {
        String source = body.getString("source");
        String sourceHash = getHash(source);
        TransPushFFMPEG transPush = TRANS_PUSH_MAP.get(sourceHash);
        if (transPush != null) {
            transPush.stop();
        }
        TRANS_PUSH_MAP.remove(sourceHash);
        return "ok";
    }

    private String getHash(String source) {
        int hash = source.hashCode();
        return Integer.toString(hash);
    }
}
